// 2025/3/17
// https://leetcode.cn/problems/binary-tree-maximum-path-sum/?envType=study-plan-v2&envId=top-100-liked
// 二叉树中的最大路径和

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    public:
        pair<int, int> dfs(TreeNode* root)
        {
            pair<int, int> ans = {0, -1001};
            if(root == nullptr) 
                return ans;
            
            pair<int, int> left = dfs(root->left);
            pair<int, int> right = dfs(root->right);
            ans.first = max(max(left.first, right.first), 0) + root->val;
            int tmp = max(left.first + right.first + root->val, ans.first);
            ans.second = max(max(left.second, right.second), tmp);
            return ans;
        }
    
        int maxPathSum(TreeNode* root) {
            pair<int, int> ans = dfs(root);
            return ans.second;
        }
    };